package mailclient.client;

import java.io.*;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.CharacterCodingException;
import java.util.logging.*;
import mailcommon.helpers.PortNumber;

public class Client {

    private SocketChannel sc;

    public Client()
            throws IOException {
        sc = SocketChannel.open();
        sc.connect(new InetSocketAddress(PortNumber.port));
    }

    protected String readFromChannel()
            throws IOException {
        ByteBuffer buf = ByteBuffer.allocate(10000);
        sc.read(buf);
        buf.flip();
        String s = "";
        while (buf.hasRemaining()) {
            s += (char) buf.get();
        }
        return s;
    }

    protected void writeToChannel(String s)
            throws IOException {
        sc.write(ByteBuffer.wrap(s.getBytes()));
    }

    protected void writeObject(Object object)
            throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);

        oos.writeObject(object);
        oos.flush();
        baos.flush();
        System.out.println(baos.toString());
        sc.write(ByteBuffer.wrap(baos.toByteArray()));
    }

    protected Object readObject()
            throws CharacterCodingException, IOException {
        ObjectInputStream ois = new ObjectInputStream(
                Channels.newInputStream(sc));
        Object readed = null;
        try {
            readed = ois.readObject();
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Client.class
                    .getName()).log(Level.SEVERE, null, ex);
        }
        return readed;
    }
}
